package com.carl.dataSources.aspect;

import com.carl.dataSources.annotation.DataSource;
import com.carl.dataSources.config.DataSourceNames;
import com.carl.dataSources.config.DataSourceSwitch;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class DataSourceAspect {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Pointcut("@annotation(com.carl.dataSources.annotation.DataSource)")
    public void dataSourcePointCut() {

    }

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();

        DataSource dataSource = method.getAnnotation(DataSource.class);
        if(dataSource == null){
            DataSourceSwitch.setDataSource(DataSourceNames.FIRST);
            logger.info("### set datasource is " + DataSourceNames.FIRST);
        }else {
            DataSourceSwitch.setDataSource(dataSource.name());
            logger.info("@@@ set datasource is " + dataSource.name());
        }

        try {
            return point.proceed();
        } finally {
            DataSourceSwitch.resetDataSource();
            logger.debug("clean datasource");
        }
    }


}
